# -*- coding=utf-8
from qcloud_cos import CosConfig, CosServiceError
from qcloud_cos import CosS3Client
from sts.sts import Sts
from django.conf import settings


def create_bucket(bucket_name, region, id=None, key=None):
    # 初始化
    secret_id = id or settings.COS_SECRET_ID  # 用户的 SecretId 访问管理中生成API秘钥
    secret_key = key or settings.COS_SECRET_KEY  # 用户的 SecretKey
    region = region  # 替换为用户的 region
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 创建桶
    response = client.create_bucket(
        Bucket=bucket_name,
        ACL="public-read"  # private 私有读写/ public-read 公有读私有写 /public-read-write 公有读写
    )

    # 跨域配置
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': "*",
                'ExposeHeader': "*",
                'MaxAgeSeconds': 500
            }
        ]
    }

    client.put_bucket_cors(
        Bucket=bucket_name,
        CORSConfiguration=cors_config
    )
    return response


def upload_file(bucket_name, region, img_obj, obj_name, id=None, key=None):
    # 初始化
    secret_id = id or settings.COS_SECRET_ID  # 用户的 SecretId 访问管理中生成API秘钥
    secret_key = key or settings.COS_SECRET_KEY  # 用户的 SecretKey
    region = region  # 替换为用户的 region
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    # 创建桶
    response = client.upload_file_from_buffer(
        Bucket=bucket_name,
        Body=img_obj,
        Key=obj_name
    )

    url = f'https://{bucket_name}.cos.{region}.myqcloud.com/{obj_name}'
    return url


def delete_file(bucket_name, region, obj_name, id=None, key=None):
    # 初始化
    secret_id = id or settings.COS_SECRET_ID  # 用户的 SecretId 访问管理中生成API秘钥
    secret_key = key or settings.COS_SECRET_KEY  # 用户的 SecretKey
    region = region  # 替换为用户的 region
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    response = client.delete_object(
        Bucket=bucket_name,
        Key=obj_name
    )
    return response


def delete_files(bucket_name, region, objects, id=None, key=None):
    # 初始化
    secret_id = id or settings.COS_SECRET_ID  # 用户的 SecretId 访问管理中生成API秘钥
    secret_key = key or settings.COS_SECRET_KEY  # 用户的 SecretKey
    region = region  # 替换为用户的 region
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)
    '''
        objects需要传入如下的数据格式
        objects = {
        "Quiet": "true",
        "Object": [
            {
                "Key": "file_name1"
            },
            {
                "Key": "file_name2"
            }
        ]
    }
    '''

    response = client.delete_objects(
        Bucket=bucket_name,
        Delete=objects
    )
    return response


def get_temp_credential(bucket, region, id=None, key=None):
    """ 获取cos上传临时凭证 """

    config = {
        # 临时密钥有效时长，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': id or settings.COS_SECRET_ID,
        # 固定密钥 key
        'secret_key': key or settings.COS_SECRET_KEY,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # "name/cos:PutObject",
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # "name/cos:UploadPart",
            # "name/cos:UploadPartCopy",
            # "name/cos:CompleteMultipartUpload",
            # "name/cos:AbortMultipartUpload",
            "*",
        ],

    }

    sts = Sts(config)
    result_dict = sts.get_credential()
    return result_dict


def get_file_info(bucket_name, region, obj_name, id=None, key=None):
    # 初始化
    secret_id = id or settings.COS_SECRET_ID  # 用户的 SecretId 访问管理中生成API秘钥
    secret_key = key or settings.COS_SECRET_KEY  # 用户的 SecretKey
    region = region  # 替换为用户的 region
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    response = client.head_object(
        Bucket=bucket_name,
        Key=obj_name
    )
    return response


def delete_bucket(bucket, region, id=None, key=None):
    """ 删除桶 """
    # 删除桶中所有文件
    # 删除桶中所有碎片
    # 删除桶
    # 初始化
    secret_id = id or settings.COS_SECRET_ID  # 用户的 SecretId 访问管理中生成API秘钥
    secret_key = key or settings.COS_SECRET_KEY  # 用户的 SecretKey
    region = region  # 替换为用户的 region
    # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224

    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
    client = CosS3Client(config)

    try:
        # 找到文件 & 删除
        while True:
            # 获取通中的key，每次1000条
            part_objects = client.list_objects(bucket)

            # 已经删除完毕，获取不到值
            contents = part_objects.get('Contents')
            if not contents:
                break

            # 批量删除
            objects = {
                "Quiet": "true",
                "Object": [{'Key': item["Key"]} for item in contents]
            }
            client.delete_objects(bucket, objects)

            if part_objects['IsTruncated'] == "false":  # 表示没有截断的后续数据了，有数据的话为true
                break

        # 找到碎片 & 删除
        while True:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])
            if part_uploads['IsTruncated'] == "false":
                break

        client.delete_bucket(bucket)
    except CosServiceError as e:  # 忽略通不存在时的报错
        pass


if __name__ == '__main__':
    COS_SECRET_ID = 'AKIDsa8RcovBSaXM3IKSVUAlHl2C9QfhWK0Y'  # 用户的 SecretId 访问管理中生成API秘钥
    COS_SECRET_KEY = 'W1ypYEnLn8TellbK3c5Qo5GF3iFpEUcY'
    # print(create_bucket("sass2-1321161744", 'ap-beijing1', id=COS_SECRET_ID, key=COS_SECRET_KEY))
    # 此方法创建成功返回值为None， 创建失败则会直接报错

    # print(delete_file("sass-1321161744", 'ap-beijing', '1920-6.jpg', id=COS_SECRET_ID, key=COS_SECRET_KEY))

    # objects = {
    #     "Quiet": "true",
    #     "Object": [
    #         {
    #             "Key": "1920-6.jpg"
    #         },
    #         {
    #             "Key": "code111.png"
    #         }
    #     ]
    # }
    # print(delete_files("sass-1321161744", 'ap-beijing', objects, id=COS_SECRET_ID, key=COS_SECRET_KEY))
    # print(get_temp_credential("sass-1321161744", 'ap-beijing', id=COS_SECRET_ID, key=COS_SECRET_KEY))
    print(get_file_info("13300009001-python-1321161744", 'ap-beijing', '13300009001_1698641604957_1920-6.jpg',
                        id=COS_SECRET_ID, key=COS_SECRET_KEY))

    res = {'Content-Type': 'image/jpeg', 'Content-Length': '1371168', 'Connection': 'keep-alive',
           'Accept-Ranges': 'bytes', 'Date': 'Mon, 30 Oct 2023 05:10:58 GMT',
           'ETag': '"73d2cfcba4c0ad8dda2b3ad3bcdca852"', 'Last-Modified': 'Mon, 30 Oct 2023 04:53:25 GMT',
           'Server': 'tencent-cos', 'Vary': 'Origin, Access-Control-Request-Headers, Access-Control-Request-Method',
           'x-cos-hash-crc64ecma': '17743605809679358904',
           'x-cos-request-id': 'NjUzZjNhZTJfN2VjZjM4MGJfMTAwZWJfZWJhYjM3OQ=='}
